import { defineStore } from 'pinia'
import { getSetting, putSetting } from '@/api'

export const useTitleStore = defineStore('title', {
  state: () => ({
    topTitle: '',
    rightTitles: ['图层控制', '目标属性', '目标消息', '战场环境'], // 更新默认值
    bottomTitles: ['目标标绘', '气象数据', '兵力部署热力图', '插件配置']
  }),

  actions: {
    /**
     * 设置顶部标题
     * @param {string} title - 新的顶部标题
     */
    setTopTitle(title) {
      this.topTitle = title
    },

    /**
     * 设置右侧标题列表
     * @param {Array<string>} titles - 新的右侧标题列表
     */
    setRightTitles(titles) {
      this.rightTitles = titles
    },

    /**
     * 设置底部标题列表
     * @param {Array<string>} titles - 新的底部标题列表
     */
    setBottomTitles(titles) {
      this.bottomTitles = titles
    },

    /**
     * 重置所有标题为默认值
     */
    resetTitles() {
      this.topTitle = ''
      this.rightTitles = []
      this.bottomTitles = []
    },

    /**
     * 从服务器获取标题设置
     * @returns {Promise<void>}
     */
    async fetchTitles() {
      try {
        const { data } = await getSetting()


        this.topTitle = data.TopTitle || this.topTitle
        this.rightTitles = data.RightTitle || this.rightTitles
        this.bottomTitles = data.BottomTitle || this.bottomTitles

      } catch (error) {
        console.error('获取标题设置失败:', error)
      }
    },

    /**
     * 更新标题设置到服务器
     * @returns {Promise<boolean>} 更新是否成功
     */
    async updateTitles() {
      try {
        const settingData = {
          TopTitle: this.topTitle,
          RightTitle: JSON.stringify(this.rightTitles),
          BottomTitle: JSON.stringify(this.bottomTitles)
        }

        const response = await putSetting(settingData)
        return response.code === 0
      } catch (error) {
        console.error('更新标题设置失败:', error)
        return false
      }
    }
  },

  // persist: {
  //   key: 'title-store',
  //   storage: localStorage
  // }
})